//
//  UserShowViewController.m
//  demoapp
//
//  Created by MingmingSun on 15/9/12.
//  Copyright (c) 2015年 pingplusplus. All rights reserved.
//

#import "UserShowViewController.h"
#import "ShowDetailViewController.h"
#import "ShowMainCollectionViewCell.h"
#import "UIImageView+AFNetworking.h"
#import "ShowAddViewController.h"
#import "MJRefresh.h"

@interface UserShowViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,ShowAddDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *cv;
@property(assign,nonatomic) BOOL refreshing;
@property(assign,nonatomic) NSInteger page;

@property(assign,nonatomic) NSInteger cusID;

@property(nonatomic,strong) NSMutableArray *showArray;

@end

@implementation UserShowViewController

@synthesize refreshing = _refreshing;
@synthesize page = _page;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"我的晒单";
        self.cusID = 0;
        self.showArray = [NSMutableArray array];
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithTitle:@"我要晒单"
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(showAdd:)];
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UINib *cellNib = [UINib nibWithNibName:@"ShowMainCell" bundle:nil];
    [self.cv registerNib:cellNib forCellWithReuseIdentifier:@"ShowMainCell"];
    _page = 0;
    _refreshing = YES;
    self.cv.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.refreshing = YES;
        self.page = 0;
        [self getShowLists];
    }];
    self.cv.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.refreshing = NO;
        self.page++;
        [self getShowLists];
    }];
    [self getCustomer];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.showArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ShowMainCell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    NSDictionary *showDic = [self.showArray objectAtIndex:indexPath.row];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:10];
    UIImageView *imageVie = (UIImageView*)[cell viewWithTag:11];
    NSDictionary *imgDic = [showDic objectForKey:@"mainPic"];
    [imageVie setImageWithURL:[NSURL URLWithString:[imgDic valueForKey:@"url"]] placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
    titleLabel.text = [NSString stringWithFormat:@"%@ ♡%d",[tooles replaceNullFromDic:showDic withKeyArray:@[@"title"]],[[showDic valueForKey:@"praise"] intValue]];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *showDic = [self.showArray objectAtIndex:indexPath.row];
    APPALL.showID = [showDic valueForKey:@"id"];
    ShowDetailViewController *vc = [ShowDetailViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)getCustomer{
    
    NSDictionary *para = @{@"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"customer_see"
                       withParameters:para
                                block:^(id object, NSError *error)
     {
         // 执行结果
         if (!error && object) {
             NSLog(@"avget:%@",object);
             NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
             switch ([[aSucData valueForKey:@"success"] intValue]) {
                 case 0:
                 {
                     [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                 }
                     break;
                 case 1:
                 {
                     NSLog(@"yeah1....");
                     self.cusID = [[[aSucData objectForKey:@"customer"] valueForKey:@"id"] integerValue];
                     [self getShowLists];
                 }
                     break;
                 default:
                     break;
             }
             [SVProgressHUD dismiss];
         } else {
             [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
         }
     }];
}

-(void)getShowLists{
    NSDictionary *para =
    @{@"gender":@"",
      @"hairType":@"",
      @"customer":[NSString stringWithFormat:@"%d",self.cusID],
      @"max":@"21",
      @"offset":[NSString stringWithFormat:@"%i",_page * 21],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"show_find" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        [self.cv.header endRefreshing];
        [self.cv.footer endRefreshing];
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    if(_refreshing){
                        [_showArray removeAllObjects];
                    }
                    NSArray *cityArray = [aSucData objectForKey:@"show"];
                    for (NSDictionary *dic in cityArray) {
                        [_showArray addObject:dic];
                    }
                    [self.cv reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

-(void)showAdd:(id)sender{
    ShowAddViewController *vc = [ShowAddViewController new];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)addFinished:(NSString *)result{
    [self.cv.header beginRefreshing];
    [self.navigationController popViewControllerAnimated:YES];
}

@end